package com.example.demo.msg.netty.client;

import com.example.demo.msg.netty.common.IMconfig;
import com.example.demo.msg.netty.common.Imessage;
import com.example.demo.msg.netty.common.MsgPackDecode;
import com.example.demo.msg.netty.common.MsgPackEncode;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NettyClient implements IMconfig,Runnable{

    private ClientHandler clientHandler = new ClientHandler();

    public static void main(String[] args) {
        try {
            new NettyClient().start();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    public void start() throws IOException{
        new Thread(this).start();
    }


    @Override
    public void run() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();

                            pipeline.addLast("frameDecoder", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                            pipeline.addLast("msgPack decoder",new MsgPackDecode());
                            pipeline.addLast("msgPack encoder",new MsgPackEncode());
                            pipeline.addLast(clientHandler);
                        }
                    });

            ChannelFuture f = bootstrap.connect(SERVER_HOST, SERVER_PORT).sync();

            Channel channel = f.channel();

            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true){

                Imessage message = new Imessage(
                        APP_IM,
                        CLIENT_VERSION,
                        1,
                        TYPE_MSG_TEXT,
                        1,
                        MSG_EMPTY);
                message.setMsg(in.readLine());

                channel.writeAndFlush(message);
            }

        } catch (Exception e) {

            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
        }
    }
}